package com.yuncheng.spcyApi.flow;

import cn.hutool.core.collection.CollectionUtil;
import org.apache.commons.collections.CollectionUtils;
import com.yuncheng.spcyApi.busService.BusService;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.entity.*;
import com.yuncheng.spcyApi.selectXzxkApi.service.PutZwxtService;
import com.yuncheng.spcyApi.selectXzxkApi.vo.PutBqbzVo;
import com.yuncheng.spcyApi.service.*;
import com.yuncheng.spcyApi.utils.GetCurrentUserUtils;
import com.yuncheng.vo.GetKsKz;
import com.yuncheng.spcyApi.vo.flow.AgentVo;
import com.yuncheng.vo.CurrentUserVo;
import com.yuncheng.spcyApi.vo.common.Result;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * 补齐补正流程-药品生产
 * @author hua
 */
@Component(value = "bqbzFlowService")
public class BqbzFlowService {

    private static final Logger log = LoggerFactory.getLogger(BqbzFlowService.class);

    @Resource
    @Lazy
    private ISpcySqsxBaiscService spcySqsxBaiscService;

    @Resource
    @Lazy
    private BusService busService;

    @Resource
    @Lazy
    private ISpcySqsxJobService spcySqsxJobService;

    @Resource
    @Lazy
    private ISysFlowNodeService sysFlowNodeService;

    @Resource
    @Lazy
    private FlowNodeService flowNodeService;

    @Resource
    private PutZwxtService putZwxtService;

    @Resource
    private IYcSysUserService sysUserService;

    /**
     * 处理流程
     * @param flowVo 流程处理参数
     * @param jobId 流程任务id
     * @param pid 流程业务id
     * @param submitType 0: 保存；1: 提交
     * @param opinion 办理意见
     * @return
     */
    public Result handleFlow(PutBqbzVo flowVo, String jobId, String pid, String submitType, String opinion){
        return this.handleFlow(flowVo, jobId, null, pid, submitType, opinion);
    }

    /**
     * 处理流程
     * @param nowJob 当前流程任务
     * @return
     */
    public Result handleFlow(PutBqbzVo flowVo, String jobId, SpcySqsxJob nowJob, String pid, String submitType, String opinion){
        if (StringUtils.isBlank(jobId)){
            return Result.error("流程任务参数不存在!");
        }

        if (nowJob == null) {
            // 当前流程任务
            nowJob = spcySqsxJobService.getById(jobId);

            if (nowJob == null){
                return Result.error("当前流程任务不存在，请重试!");
            }
        }

        pid = nowJob.getFpid();
        if (StringUtils.isBlank(pid)){
            return Result.error("业务参数为空!");
        }

        // 提交按钮
        if (submitType.equals(SpcyFlowConstant.SUBMIT_TYPE_SUBMIT)) {

        }

        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        if (currentUser == null){
            return Result.error("登录已失效，请重新登录");
        }

        if (StringUtils.isBlank(nowJob.getFhjmc())){
            return Result.error("流程环节名称为空");
        }

        // 流程环节处理
        Result httpResult = handleNodeName(flowVo, submitType, nowJob, pid, opinion);
        if (!httpResult.isSuccess()) {
            return httpResult;
        }



        return Result.ok("操作成功");
    }

    /**
     * 流程环节处理
     * @param pid 业务id
     * @param flowVo 需要修改的字段内容
     * @param job 流程任务job
     * @param opinion 办理意见
     * @param submitType 提交、保存类型
     * @return true(),false(提示信息)
     */
    public Result handleNodeName(PutBqbzVo flowVo,String submitType, SpcySqsxJob job, String pid, String opinion){
        HashMap<String, Object> map = flowVo.getMap();
        String smgflag = flowVo.getSmgflag(); // 短信发送标志
        String smsContent = flowVo.getSmsContent(); // 发送短信内容

        Result res = null;

        // 保存按钮
        if (submitType.equals(SpcyFlowConstant.SUBMIT_TYPE_SAVE)){

        }

        // 提交按钮
        if (submitType.equals(SpcyFlowConstant.SUBMIT_TYPE_SUBMIT)){

            if (job == null){
                return Result.error("当前流程任务不存在");
            }

            if (StringUtils.isBlank(job.getFhjmc())){
                return Result.error("当前流程任务环节名称丢失");
            }

            // 流程任务id
            String jobid = job.getId();

            // 提交流程任务,待办人是否为空，指定待办人
            if (StringUtils.isBlank(flowVo.getDbrid())) {
                // 按审查模式-提交-流程任务
                res = this.passJob(pid, jobid, job, opinion, flowVo.getNextNode(),flowVo.getNextNodeId(), null);
            }else {
                // 按审查模式-提交-流程任务
                res = this.passJob(pid, jobid, job, opinion, flowVo.getNextNode(),flowVo.getNextNodeId(),flowVo.getDbrid());
            }

            if (!res.isSuccess()){
                return res;
            }else {
                /**
                 * 接收返回的流程任务，如果返回的流程任务id不相等，发送短信
                 * 发送下环节短信
                 */
                if (StringUtils.isNotBlank(smgflag) && (smgflag.equals("是") || smgflag.equals("true"))){
                    busService.sendSmsToNextJob(jobid, smsContent);
                }
            }
        }

        return Result.ok("提交成功");
    }

    /**
     * 提交流程-并创建指定流程
     * @param jobid 当前流程任务id
     * @param pid 流程业务id
     * @param opinion 办理意见
     */
    public Result passNextNodeFlow(PutBqbzVo flowVo, String jobid, String pid, String opinion){
        return this.passNextNodeFlow(flowVo, jobid, null, pid, opinion);
    }
    public Result passNextNodeFlow(PutBqbzVo flowVo, String jobid, SpcySqsxJob nowJob, String pid, String opinion){
        if (nowJob == null) {
            nowJob = spcySqsxJobService.getById(jobid);
            if (nowJob == null) {
                return Result.error("没有相匹配的流程数据！");
            }
        }

        pid = nowJob.getFpid();
        flowVo.setSqsxid(pid);
        flowVo.setFsqsxid(pid);
        flowVo.setDbrid(null);

        Result httpResult = null;

//        if (nowJob.getFhjmc().equals(SpcyFlowConstant.HJMC_CLSC)){
        if (nowJob.getFhjmc().equals(SpcyFlowConstant.HJMC_JSSP)){

            if (StringUtils.isBlank(flowVo.getFbqbzyj())){
                return Result.error("补齐补正意见为空！");
            }

            opinion = flowVo.getFbqbzyj();
//            String flowCode = SpcyFlowConstant.getBqbzFlowCodeByYwflcode(spcySqsxBaiscService.getYwflCodeBySqsxId(pid));
            String flowCode = SpcyFlowConstant.getFlowCodeByYwflcode(null, null);

            List<SysFlowNode> nodeByCodeJdmc = sysFlowNodeService.getNodeByCodeJdmc(flowCode, SpcyFlowConstant.HJMC_ZHPD);
            if (CollectionUtil.isEmpty(nodeByCodeJdmc)){
                return Result.error("流程结点配置为空！");
            }

            httpResult = flowNodeService.passJob(flowCode, pid, jobid, opinion, nodeByCodeJdmc.get(0).getId(), "");

            if (httpResult.isSuccess()){
                /*String ywflcode = spcySqsxBaiscService.getYwflCodeBySqsxId(pid);
                if (ywflcode.equals(SpcyConstant.YWFL_CODE_YPSC)) {*/
                    putZwxtService.pushQyBqbzNoticeNew(flowVo);
//                }
            }else {
                return httpResult;
            }

        }else if (nowJob.getFhjmc().equals(SpcyFlowConstant.HJMC_BQBZSH)){

            httpResult = this.handleFlow(flowVo, jobid, nowJob, "", SpcyFlowConstant.SUBMIT_TYPE_SUBMIT, opinion);

            if (httpResult.isSuccess()){
                putZwxtService.pushQyBqbzNoticeWc(nowJob.getFpid(), jobid, nowJob);

            }else {
                return Result.error(httpResult.getMessage());
            }

        }else {

            return Result.error(nowJob.getFhjmc()+"该结点没有配置处理！");
        }

        if (!httpResult.isSuccess()){
            return httpResult;
        }

        return Result.ok();
    }

    /**
     * 提交流程
     * @param pid 业务id
     * @param jobid 流程任务id
     * @param job 当前流程任务
     * @param opinion 办理意见
     * @param nextNodeName 下环节结点名称
     * @param nextNodeId 下环节结点id
     * @param nextNodeDbrIds 下环节待办人
     * @return
     */
    private Result passJob(String pid,String jobid,SpcySqsxJob job, String opinion,String nextNodeName,String nextNodeId,String nextNodeDbrIds){
        if (job == null){
            job = spcySqsxJobService.getById(jobid);
        }
        String jobNodeName = job.getFhjmc(); // 当前环节名称

        String ywflcode = spcySqsxBaiscService.getYwflCodeBySqsxId(pid);

        Result httpResult = null;

//        if (ywflcode.equals(SpcyConstant.YWFL_CODE_YPSC)){
            // 是否为最终结点
            if (StringUtils.isNotBlank(jobNodeName) && jobNodeName.equals(SpcyFlowConstant.HJMC_BQBZSH)){
                //办理掉当前环节
                httpResult = flowNodeService.doJob(job, opinion);
            }else {
                String lcmbCode = SpcyFlowConstant.getBqbzFlowCodeByYwflcode(ywflcode);

                httpResult = flowNodeService.passJob(lcmbCode, pid, jobid, opinion, nextNodeId, nextNodeDbrIds);
            }
        /*}else {
                String lcmbCode = SpcyFlowConstant.getBqbzFlowCodeByYwflcode(ywflcode);
                httpResult = flowNodeService.passJob(lcmbCode, pid, jobid, opinion, nextNodeId, nextNodeDbrIds);
        }*/

        if (!httpResult.isSuccess()){
            return httpResult;
        }

        return Result.ok("success");
    }



    /**
     * 获取下环节待办人
     * @param jobid
     * @param job
     * @return
     */
    public Map getNextNodeDbr(String jobid, SpcySqsxJob job){
        Map map = new HashMap();

        Map nextDbr = this.getNowJobInNextDbrAndHandlePageUrl(jobid, job);
        String nextNodeId = ""; // 下结点id
        String nextNode = "办结"; // 下结点名称
        if (nextDbr.get("nextNode") != null) {
            SysFlowNode nextFlowNode = (SysFlowNode) nextDbr.get("nextNode");
            nextNodeId = nextFlowNode.getId();
            nextNode = nextFlowNode.getFjdmc();
        }
        List<AgentVo> dbrListByMap = this.getDbrListByMap(nextDbr);

        map.put("nextNodeDbrList", dbrListByMap); // 下环节待办人list

        map.put("nextNode", nextNode); // 下流程结点名称
        map.put("nextNodeId", nextNodeId); // 下流程结点id

        return map;
    }

    /**
     * 获取下一个环节名称和待办人
     * @param job 流程任务
     * @param jobid 流程任务id
     * @return
     * {
     *     dbrId
     *     dbr:
     *     nextNode：下流程结点
     *     handlePageUrl：办理页面路径
     * }
     */
    private Map getNowJobInNextDbrAndHandlePageUrl(String jobid, SpcySqsxJob job){
        if (job == null && StringUtils.isNotBlank(jobid)){
            job = spcySqsxJobService.getById(jobid);
        }
        String flowCode = SpcyFlowConstant.getBqbzFlowCodeByYwflcode(spcySqsxBaiscService.getYwflCodeBySqsxId(job.getFpid()));
        return flowNodeService.getNowJobInNextDbrAndHandlePageUrl(flowCode, job, null);
    }

    /**
     * 将待办人map转为List
     * @param map { dbrId: 待办人id ; dbr: 待办人 }
     */
    private List<AgentVo> getDbrListByMap(Map map){
        String dbrids = map.get("dbrId").toString(); // 待办人id
        String dbrs = map.get("dbr").toString(); // 待办人

        List<AgentVo> agentList = new ArrayList<>();

        if (StringUtils.isNotBlank(dbrids)) {
            String agentIds[] = dbrids.split(",|，");
            String agentNames[] = dbrs.split(",|，");

            for (int i = 0; i < agentIds.length; i++) {
                AgentVo agentVo = new AgentVo();
                agentVo.setDbrid(agentIds[i]);
                agentVo.setDbr(agentNames[i]);
                agentList.add(agentVo);
            }
        }

        return agentList;
    }

    /**
     * 获取当前环节待办人
     * @param pid 业务id
     * @param nodeName 环节名称
     * @return
     */
    public Map getNodeDbr(String pid, String nodeName){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";

        /** 获取对应科室 */
        String deptName = SpcyConstant.getYwclNameByCode(spcySqsxBaiscService.getYwflCodeBySqsxId(pid));

        // 审核
        if (nodeName.equals(SpcyFlowConstant.HJMC_BQBZSH)){
            // 科室负责人
            Map kzMap = getKsfzrByDeptName(deptName);
            dbrId = kzMap.get("dbrId").toString();
            dbr = kzMap.get("dbr").toString();
        }


        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

    // 对应科室的 科室负责人
    public Map getKsfzrByDeptName(String deptName){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";
        List<GetKsKz> ksKzObject = new ArrayList<>();
        ksKzObject = sysUserService.getKsKzObject(deptName, SpcyConstant.GW_NAME_KZ);
        if (CollectionUtils.isNotEmpty(ksKzObject)) {
            for (GetKsKz ksKz : ksKzObject) {
                dbrId += ksKz.getId()+",";
                dbr += ksKz.getRealname()+",";
            }
        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }
}
